<template>
  <div class="page_view flex">
    <van-nav-bar
      style="background: #0caaed"
      left-arrow
      @click-left="$router.back()"
    >
      <template slot="title">
        <span style="color: #ffffff;">{{$route.query.id ? '编辑' : '新增'}}便签</span>
      </template>
      <template slot="left">
        <van-icon name="arrow-left" size="20px" color="#ffffff"/>
      </template>
      <template slot="right">
        <div @click="submitData" class="flex_center">
          <span style="color:#ffffff;">提交</span>
          <van-icon name="success" size="20px" color="#ffffff" @click="showTip = true"/>
        </div>
      </template>
    </van-nav-bar>
    <div class="flex1 at pd10">
      <div id="editor"></div>
      <div class="pd10">
        <van-tag
          closeable
          size="medium"
          type="primary"
          v-for="(item, index) in noteItem.tags"
          :key="index"
          @close="onDelTag(index)"
          :color="tagsColor[index % tagsColor.length]"
          style="margin: 0 5px 5px 0;"
        >
          {{item}}
        </van-tag>
      </div>
      <van-field
        v-model="tag"
        center
        clearable
        label="添加标签"
        placeholder="输入标签名称"
        style="background: #F1F1F1;border-radius: 1rem"
      >
        <template #button>
          <van-button icon="plus" type="primary" round @click="addTag" size="small"/>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'
import {mapState} from 'vuex'
export default {
  name: 'edit',
  data () {
    return {
      noteItem: {
        tags: [],
        content: ''
      },
      loading: false,
      editor: null,
      tag: ''
    }
  },
  computed: {
    ...mapState(['tagsColor'])
  },
  methods: {
    initData(){
      let editor = new E('#editor');
      // 将图片大小限制为 3M
      editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
      editor.customConfig.zIndex = 10;
      editor.customConfig.customUploadImg = (files, insert) => {
        // 此处不能用循环上传 会出问题 使用递归
        let len = 0,
          // eslint-disable-next-line no-unused-vars
          uploadImg = ()=> {
            let formData = new FormData()
            formData.append('file', files[len])
            this.request.uploadIng(formData)
              .then(res=>{
                insert(res.data);
                len += 1;
                if (files[len]){
                  uploadImg()
                }
              }).catch(()=>{
                len += 1;
                if (files[len]){
                  uploadImg()
                }
              })
          };
        uploadImg()
      };
      editor.create();
      this.editor = editor;
      if (this.$route.query.id) {
        this.getNote()
      }
    },
    getNote(){
      this.request.getNoteById({id: this.$route.query.id})
        .then(res => {
          if (res.data){
            let noteItem = res.data;
            noteItem.tags = noteItem.tags.split(',');
            this.noteItem = noteItem
            this.editor.txt.html(noteItem.content)
          }
        })
    },
    onDelTag(index){
      this.noteItem.tags.splice(index, 1)
    },
    addTag(){
      if (this.tag){
        this.noteItem.tags.push(this.tag);
        this.tag = '';
      }
    },
    submitData(){
      let params = {
          content: this.editor.txt.html(),
          tags: this.noteItem.tags.join(',')
        },
        fn = 'saveNote',
        message = '新增';
      if (this.$route.query.id){
        params.id = ~~this.$route.query.id;
        fn = 'updateNote';
        message = '修改'
      }
      this.request[fn](params)
        .then(res=>{
          this.$dialog.alert({
            title:'提示',
            message: message + ['失败', '成功'][res.data]
          }).then(() => {
            if (res.data === 1) {
              if (params.id) {
                this.getNote()
              } else if (!params.id) {
                this.$router.back()
              }
            }
          });
        })
    }
  },
  mounted() {
    this.initData()
  }
}
</script>

<style scoped lang="less">
  .flex1.at{
    overflow-x: hidden;
  }
</style>
